public class HashBucket {
    static class Node {
        public int key;
        public int val;
        public Node next;

        public Node(int key, int val) {
            this.key = key;
            this.val = val;
        }
    }

    public Node[] hashTable;
    public int usedSize;

    public HashBucket() {
        hashTable = new Node[10];
    }

    private double loadFactor() {
        return usedSize * 1.0 / hashTable.length;
    }

    private void resize() {
        Node[] tmpArr = new Node[hashTable.length * 2];
        //扩容之后，key的哈希地址可能改变，要遍历数组，将所有元素 重新散列 到新数组中
        for(int i = 0; i < hashTable.length; i++) {
            Node cur = hashTable[i];
            while(cur.next != null) {
                int newIndex = cur.key % tmpArr.length;
                //头插
                Node curNext = cur.next;
                cur.next = tmpArr[newIndex];
                tmpArr[newIndex] = cur;
                cur = curNext;
            }
        }
        hashTable = tmpArr;
    }

    public void put(int key, int val) {
        int index = key % hashTable.length;
        Node cur = hashTable[index];
        while (cur.next != null) {
            if (cur.key == key) {
                cur.val = val;
                return;
            }
            cur = cur.next;
        }
        cur.next = new Node(key, val);
        usedSize++;
        if(loadFactor() >= 0.75) {
            resize();
        }
    }

    public int get(int key) {
        int index = key % hashTable.length;
        Node cur = hashTable[index];
        while(cur != null) {
            if(cur.key == key) {
                return cur.val;
            }
            cur = cur.next;
        }
        return -1;
    }
}
